package com.sky.chapter3.lockSupport;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 异常：
 * condition.await();和condition.signal();都触发了IllegalMonitorStateException异常
 * <p>
 * 原因：调用condition中线程等待和唤醒的方法的前提是，要在lock和unlock方法中,要有锁才能调用
 *
 * Object和 Condition使用的限制条件
 *
 * 线程先要获得并持有锁，必须在锁块(synchronized或lock)中
 *
 * 必须要先等待后唤醒，线程才能够被唤醒
 */
public class LockSupportDemo5 {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();


        //线程没有加锁, 使用 await 会报错;
        new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "start");
                condition.await();
                System.out.println(Thread.currentThread().getName() + "\t" + "被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        //暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(3L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            try {
                condition.signal();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + "通知了");
        }, "t2").start();

    }
}
